package com.xixibaby.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xixibaby.core.Assert;
import com.xixibaby.core.login.AuthLocal;
import com.xixibaby.core.login.LoginInfoVO;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 自定义填充公共 name 字段
 *
 * @author tomj
 * @date 2018/12/11
 */
public class DateMetaObjectHandler implements MetaObjectHandler {
    private final static String UPDATE_TIME = "updateTime";
    private final static String CREATE_TIME = "createTime";
    private final static String LOGIC_DELETE = "deleted";
    private final static String VERSION = "version";
    private final static String UPDATE_BY = "updateBy";
    private final static String CREATE_BY = "createBy";
    /**
     * 插入填充，字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(CREATE_TIME, metaObject);
        Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
        Object deleted = getFieldValByName(LOGIC_DELETE, metaObject);
        Object version = getFieldValByName(VERSION, metaObject);

        Object createBy = getFieldValByName(CREATE_BY, metaObject);
        Object updateBy = getFieldValByName(UPDATE_BY, metaObject);
        if (createTime == null || updateTime == null) {
            Date date = new Date();
            if (createTime == null) {
                setFieldValByName(CREATE_TIME, date, metaObject);
            }
            LoginInfoVO accountInfo = AuthLocal.getAuthVO();
            if (createBy == null && Assert.notEmpty(accountInfo)) {

                setFieldValByName(CREATE_BY, accountInfo.getUserId(), metaObject);
                if(updateBy == null){
                    setFieldValByName(UPDATE_BY, accountInfo.getUserId() , metaObject);
                }

            }

            if (updateTime == null) {
                setFieldValByName(UPDATE_TIME, date, metaObject);
            }
        }

        if (deleted == null) {
            setFieldValByName(LOGIC_DELETE, 0, metaObject);
        }
        if (version == null) {
            setFieldValByName(VERSION, 1, metaObject);
        }

    }

    /**
     * 更新填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //mybatis-plus版本2.0.9+
        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        Object updateBy = getFieldValByName(UPDATE_BY, metaObject);
        LoginInfoVO accountInfo = AuthLocal.getAuthVO();
        if(updateBy == null && Assert.notEmpty(accountInfo)){
            setFieldValByName(UPDATE_BY, accountInfo.getUserId() , metaObject);
        }
    }
}